/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.prodcons.threads;

import ua.yandex.prodcons.utilconcurrent.BufferUtils;

/**
 *
 * @author vlad
 */
public class RoundedBuffer {

    private final BufferUtils state = new BufferUtils();

    private Object[] items;
    private int putptr;
    private int takeptr;
    private int count;
    
    private RoundedBuffer() {
    }
    
    public RoundedBuffer(int size) {
        items = new Object[size];
    }

    public void put(Object x) throws InterruptedException {
        state.lock.lock();
        try {
            while (count == items.length) {
                state.notFull.await();
            }
            items[putptr] = x;
            putptr++;
            if (putptr == items.length) {
                putptr = 0;
            }
            count++;
            state.notEmpty.signal();
        } finally {
            state.lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        state.lock.lock();
        try {
            while (count == 0) {
                state.notEmpty.await();
            }
            Object x = items[takeptr];
            takeptr++;
            if (takeptr == items.length) {
                takeptr = 0;
            }
            count--;
            state.notFull.signal();
            return x;
        } finally {
            state.lock.unlock();
        }
    }
}
